package com.engr.lyx.platform.biz.controller;

import com.engr.lyx.common.base.ResultBody;
import com.engr.lyx.common.http.OpenRestTemplate;
import com.engr.lyx.common.utils.ResultUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @program: blog
 * @desc:
 * @author: lyx
 * @date: 2019-04-08 17:58
 **/
@RestController
public class AdminController {

    @Autowired
    private OpenRestTemplate restTemplate;

    @Autowired
    private ResourceServerProperties resourceServerProperties;

    @PostMapping(value = "/login/token")
    private ResultBody getToken(@RequestParam String username, @RequestParam String password, @RequestHeader HttpHeaders headers) {

        // 使用oauth2密码模式登录.
        MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
        postParameters.add("username", username);
        postParameters.add("password", password);
        postParameters.add("client_id", resourceServerProperties.getClientId());
        postParameters.add("client_secret", resourceServerProperties.getClientSecret());
        postParameters.add("grant_type", "password");
        postParameters.add("scope", "server");
        // 使用客户端的请求头,发起请求
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        // 强制移除 原来的请求头,防止token失效
        headers.remove(HttpHeaders.AUTHORIZATION);
        HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity(postParameters, headers);
        Map result = restTemplate.postForObject("http://localhost:8080/auth/oauth/token", request, Map.class);
        return ResultUtils.success(result);
    }
}
